(function($) {
    'use strict';

    $.layer = function(method) {
        var pluginName = "MobLayer";

        var defaults = {
            type: "alert",
            content: "",
            title: "",
            time: 0,
            width: '',
            heihgt: '',
            shade: true,
            shadeClose: false,
            style: "",
            className: "",
            btn: "",
            btnClass: "",
            btnFunc: "",
            fullSize: false,
            zIndex: '',
            ok: '',
            cancel: '',
            success: function() {
                return false;
            },
            end: function() {
                return false;
            }
        };

        var main = {
            init: function(layerId, opts) {
                var shadeBox = '';
                if ($('.m-layer-shade').length === 0 && opts.shade) {
                    shadeBox = '<div class="m-layer-shade"></div>';
                }

                var layerTitle = opts.title ? '<div class="m-layer-title">' + opts.title + '</div>' : '';

                var layerBtm = '',
                    layerBtn = opts.btn,
                    layerBtnClass = opts.btnClass;

                var alertBtm = function() {
                    var btnTxt = layerBtn[0] ? layerBtn[0] : '确定';
                    layerBtm += '<div class="m-layer-bottom"><div m-role="Button" class="layer-ok">' + btnTxt + '</div></div>';
                };

                var confirmBtm = function() {
                    var btn1 = layerBtn[0] ? layerBtn[0] : '取消',
                        btn2 = layerBtn[1] ? layerBtn[1] : '确定';
                    layerBtm += '<div class="m-layer-bottom"><div m-role="Button" class="layer-cancel">' + btn1 + '</div><div m-role="Button" class="layer-ok">' + btn2 + '</div></div>';
                };

                var normalBtm = function() {
                    if (layerBtn) {
                        layerBtm += '<div class="m-layer-bottom">';

                        for (var i = 0; i < layerBtn.length; i++) {
                            var btnClass = layerBtnClass[i] ? layerBtnClass[i] : '';
                            layerBtm += '<div m-role="Button" class="layer-btn ' + btnClass + '">' + layerBtn[i] + '</div>';
                        }
                        layerBtm += '</div>';
                    }
                };

                var msgBoxStyle = '';
                switch (opts.type) {
                    case "alert":
                        alertBtm();
                        break;
                    case "confirm":
                        confirmBtm();
                        break;
                    case "message":
                        layerBtm = '';
                        msgBoxStyle = ' m-layer-msg ';
                        break;
                    default:
                        normalBtm();
                        break;
                }


                var layerZindex = opts.zIndex ? " z-index:" + opts.zIndex + "; " : '',
                    layerClass = opts.className ? opts.className : '',
                    initW = opts.width ? " width:" + opts.width + '; ' : '',
                    initH = opts.height ? " height:" + opts.height + '; ' : '',
                    layerWidth = opts.fullSize ? " width:100%;max-width:100%;" : initW,
                    layerHeight = opts.fullSize ? " height:100%;" : initH,
                    layerStyle = layerWidth + layerHeight + opts.style;
                layerStyle = layerStyle ? ' style="' + layerStyle + '"' : '';

                var layout = ['<div class="m-layer-contain" style="' + layerZindex + '"  layerid="' + layerId + '">',
                    '<div class="m-layer-box ' + msgBoxStyle + layerClass + '" ' + layerStyle + '>',
                    layerTitle,
                    '<div class="m-layer-main">' + opts.content + '</div>',
                    layerBtm,
                    '</div>',
                    '</div>'
                ].join('');

                var layerHtml = shadeBox + layout;

                $("body").append(layerHtml);


                $("body").data("layer-" + layerId, opts);
                $("body").data("layer-currentId", layerId);

                if (typeof opts.success == "function") opts.success.call(this);

                main._event(layerId);
            },
            _event: function(layerId) {
                var opts = $("body").data("layer-" + layerId),
                    layerSelector = $('[layerid=' + layerId + ']');

                var okBtn = layerSelector.find(".layer-ok"),
                    cancelBtn = layerSelector.find(".layer-cancel");

                if (okBtn.length > 0) {
                    okBtn.on('click', function(ev) {
                        var idx = $(this).parents(".m-layer-contain").attr("layerid"),
                            okOpts = $("body").data("layer-" + idx);
                        if (okOpts.ok) {
                            okOpts.ok.call(this, idx);
                        } else {
                            main.close(idx);
                        }

                        return false;
                    });
                }

                if (cancelBtn.length > 0) {
                    cancelBtn.on('click', function(ev) {
                        var idx = $(this).parents(".m-layer-contain").attr("layerid"),
                            okOpts = $("body").data("layer-" + idx);
                        if (okOpts.cancel) {
                            okOpts.cancel.call(this, idx);
                        } else {
                            main.close(idx);
                        }

                        return false;
                    });
                }


                var layerBtn = layerSelector.find(".layer-btn");
                if (layerBtn.length > 0 && opts.btnFunc) {
                    layerBtn.on('click', function(ev) {
                        var idx = $(this).index();
                        opts.btnFunc[idx].call(this);
                        return false;
                    });
                }


                var layerClose = layerSelector.find(".layer-close");
                layerClose.on('click', function(ev) {
                    main.close();
                    return false;
                });

                if (opts.shadeClose) {
                    $(".m-layer-contain").on('click', function(ev) {
                        var target = $(ev.target);

                        if (target.hasClass('m-layer-contain')) {
                            main.closeAll();
                        }
                    });
                }

                if (opts.time) {
                    setTimeout(function() {
                        main.close(layerId);
                    }, opts.time);
                }
            },
            open: function(layerId) {
                var opts = $("body").data("layer-" + layerId);
                if (opts.shade) {
                    $(".m-layer-shade").addClass('on');
                }
                $('[layerid=' + layerId + ']').addClass('on');
            },
            close: function(layerId) {
                var opts = $("body").data("layer-" + layerId);

                $('.m-layer-shade').removeClass('on');
                $('[layerid=' + layerId + ']').remove();
                $(".m-layer-shade").removeData("layer-" + layerId);

                if (typeof opts.end == "function") opts.end.call(this, layerId);
            },
            closeAll: function() {
                var layerId = $("body").data("layer-currentId"),
                    opts = $("body").data("layer-" + layerId);

                $('.m-layer-shade').removeClass('on');
                $(".m-layer-contain").remove();
                $(".m-layer-shade").removeData();

                if (typeof opts.end == "function") opts.end.call(this, layerId);
            }
        };

        var methods = {
            init: function(options) {
                var opts = $.extend({}, defaults, options || {}),
                    layerId = $(".m-layer-contain").last().attr("layerid");

                layerId = layerId ? parseInt(layerId, 10) + 1 : 1;

                main.init(layerId, opts);
                main.open(layerId, opts);

                return layerId;
            },
            close: function(layerId) {
                main.close(layerId);
            },
            closeAll: function() {
                main.closeAll();
            }

        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            alert(pluginName + '控件中不存在名为：' + method + ' 的方法或属性！');
        }
    };

    $.toast = function(content, end, time, zIndex) {
        content = '<div m-role="cell" m-layout="fit" m-align="center" m-valign="middle">' + content + '</div>';
        $.layer({
            type: "message",
            content: content,
            shade: false,
            time: time ? time : 2000,
            zIndex: zIndex ? zIndex : 20001,
            end: end
        });
    };

    $.fn.MobTextField = function(method) {
        var pluginName = "MobTextField",
            OB = this,
            $OB = $(this);

        var main = {
            init: function(obj) {

                obj = obj ? obj : $OB;
                if (obj.find('input').length > 0) return false;
                main._html(obj);
                main._event(obj);
            },
            _html: function(obj) {
                var textType = obj.attr("m-type"),
                    textMaxLength = obj.attr('m-maxlength'),
                    textMinLength = obj.attr('m-minlength'),
                    textName = obj.attr('m-name'),
                    textValue = obj.attr('m-value'),
                    textPlaceholder = obj.attr('m-placeholder'),
                    textDisabled = obj.attr('m-disabled');

                textType = textType ? ' type="' + textType + '"' : ' type="text"';
                textMaxLength = textMaxLength ? ' maxlength="' + textMaxLength + '"' : '';
                textMinLength = textMinLength ? ' minlength="' + textMinLength + '"' : '';
                textName = textName ? ' name="' + textName + '"' : '';
                textValue = textValue ? ' value="' + textValue + '"' : '';
                textPlaceholder = textPlaceholder ? ' placeholder="' + textPlaceholder + '"' : '';
                textDisabled = textDisabled ? ' disabled="' + textDisabled + '"' : '';

                var inputHtml = ['<input ', textType, textName, textValue, textPlaceholder, textMaxLength, textMinLength, textDisabled, '" />', '<div class="text-field-clear"><div m-icon="clear"></div></div>'].join('');
                obj.addClass('text-field').append(inputHtml);
            },
            _event: function(obj) {
                obj.find('input').on('focus', function() {
                        var _this = $(this);
                        _this.addClass('onfocus');
                        main._fn.checkNull($(this));
                    })
                    .on('blur', function() {
                        $(this).removeClass('onfocus');
                        obj.removeClass('show-clear-btn');
                    });

                main._fn.input(obj);
                main._fn.change(obj);

                obj.on('click', '.text-field-clear', function() {
                    var _this = $(this);
                    obj.removeClass('show-clear-btn');
                    _this.prev('input').val('').focus();
                    obj.attr('m-value', '');
                });

                $(document).on('touchmove', function() {
                    var input = obj.find('input');
                    if (input.hasClass('onfocus')) input.blur();
                });

            },
            _fn: {
                checkNull: function(obj) {
                    var val = obj.val();
                    if (val === '') {
                        obj.parents('.text-field').removeClass('show-clear-btn');
                    } else {
                        obj.parents('.text-field').addClass('show-clear-btn');
                    }
                },
                disabled: function(obj) {
                    obj.attr('m-disabled', 'true').find('input').prop('disabled', true);
                },
                undisabled: function(obj) {
                    obj.removeAttr('m-disabled').find('input').prop('disabled', false);
                },
                input: function(obj) {
                    obj.on('input', 'input', function() {
                        var _this = $(this);
                        obj.attr('m-value', _this.val());
                        main._fn.checkNull(_this);
                    });
                },
                change: function(obj) {
                    obj.on('change', 'input', function() {
                        obj.attr('m-value', $(this).val());
                        main._fn.checkNull($(this));
                    });
                }
            }
        };

        var methods = {
            init: function(options) {
                if ($OB.length === 0) return false;
                if ($OB.length > 1) {
                    var textFields = {},
                        textFieldId = $('[m-textfield]').length > 0 ? $('[m-textfield]').attr('m-textfield') : 0;
                    textFieldId = parseInt(textFieldId, 10);
                    $OB.each(function() {
                        var _this = $(this);
                        if (typeof _this.attr('m-textfield') != 'undefined') return false;
                        textFieldId++;
                        _this.attr('m-textfield', textFieldId);
                        main.init(_this);
                        textFields[textFieldId] = _this;
                    });

                    return textFields;
                }

                main.init();
            },
            value: function() {
                return $OB.attr('m-value');
            },
            setValue: function(val) {
                $OB.attr('m-value', val).find('input').val(val);
                main._fn.checkNull($OB);
            },

            clear: function() {
                $OB.attr('m-value', '').find('input').val('');
                main._fn.checkNull($OB);
            },
            placeholder: function(val) {
                $OB.attr('m-placeholder', val).find('input').attr('placeholder', val);
            },
            disabled: function() {
                main._fn.disabled($OB);
            },
            undisabled: function() {
                main._fn.undisabled($OB);
            }
        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            alert(pluginName + '控件中不存在名为：' + method + ' 的方法或属性！');
        }
    };

    $.fn.MobTextarea = function(method) {
        var pluginName = "MobTextarea",
            OB = this,
            $OB = $(this);

        var main = {
            init: function(obj) {

                obj = obj ? obj : $OB;
                if (obj.find('textarea').length > 0) return false;
                main._html(obj);
                main._event(obj);
            },
            _html: function(obj) {
                var textareaType = obj.attr("m-type"),
                    textareaMaxLength = obj.attr('m-maxlength'),
                    textareaMinLength = obj.attr('m-minlength'),
                    textareaValue = obj.attr('m-value'),
                    textareaPlaceholder = obj.attr('m-placeholder'),
                    textareaDisabled = obj.attr('m-disabled');

                textareaType = textareaType ? ' type="' + textareaType + '"' : ' type="text"';
                textareaMaxLength = textareaMaxLength ? ' maxlength="' + textareaMaxLength + '"' : '';
                textareaMinLength = textareaMinLength ? ' minlength="' + textareaMinLength + '"' : '';
                textareaValue = textareaValue ? ' value="' + textareaValue + '"' : '';
                textareaPlaceholder = textareaPlaceholder ? ' placeholder="' + textareaPlaceholder + '"' : '';
                textareaDisabled = textareaDisabled ? ' disabled="' + textareaDisabled + '"' : '';

                var textareaHtml = ['<textarea ', textareaType, textareaValue, textareaPlaceholder, textareaMaxLength, textareaMinLength, textareaDisabled, '" >', textareaValue, '</textarea>', '<div class="text-field-clear"><div m-icon="clear"></div></div>'].join('');
                obj.addClass('textarea-field').append(textareaHtml);

            },
            _event: function(obj) {
                obj.find('textarea').on('focus', function() {
                        var _this = $(this);
                        _this.addClass('onfocus');
                        main._fn.checkNull($(this));
                    })
                    .on('blur', function() {
                        $(this).removeClass('onfocus');
                        obj.removeClass('show-clear-btn');
                    });

                main._fn.input(obj);
                main._fn.change(obj);

                obj.on('click', '.text-field-clear', function() {
                    var _this = $(this);
                    obj.removeClass('show-clear-btn');
                    _this.prev('textarea').val('').focus();
                    obj.attr('m-value', '');
                });

                $(document).on('touchmove', function() {
                    var textarea = obj.find('textarea');
                    if (textarea.hasClass('onfocus')) textarea.blur();
                });

            },
            _fn: {
                checkNull: function(obj) {
                    var val = obj.val();
                    if (val === '') {
                        obj.parents('.textarea-field').removeClass('show-clear-btn');
                    } else {
                        obj.parents('.textarea-field').addClass('show-clear-btn');
                    }
                },
                disabled: function(obj) {
                    obj.attr('m-disabled', 'true').find('textarea').prop('disabled', true);
                },
                undisabled: function(obj) {
                    obj.removeAttr('m-disabled').find('textarea').prop('disabled', false);
                },
                input: function(obj) {
                    obj.on('input', 'textarea', function() {
                        var _this = $(this);
                        obj.attr('m-value', _this.val());
                        main._fn.checkNull(_this);
                    });
                },
                change: function(obj) {
                    obj.on('change', 'textarea', function() {
                        obj.attr('m-value', $(this).val());
                        main._fn.checkNull($(this));
                    });
                }
            }
        };

        var methods = {
            init: function(options) {
                if ($OB.length === 0) return false;
                if ($OB.length > 1) {
                    var textareas = {},
                        textareaId = $('[m-textarea]').length > 0 ? $('[m-textarea]').attr('m-textarea') : 0;
                    textareaId = parseInt(textareaId, 10);
                    $OB.each(function() {
                        var _this = $(this);
                        if (typeof _this.attr('m-textarea') != 'undefined') return false;
                        textareaId++;
                        _this.attr('m-textarea', textareaId);
                        main.init(_this);
                        textareas[textareaId] = _this;
                    });

                    return textareas;
                }

                main.init();
            }
        };

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            alert(pluginName + '控件中不存在名为：' + method + ' 的方法或属性！');
        }
    };

    var mobui = {
        init: function() {
            $('[m-role="TextField"]').MobTextField();
            $('[m-role="Textarea"]').MobTextarea();
        },
        bind: function(el) {
            $(el).find('[m-role="TextField"]').MobTextField();
            $(el).find('[m-role="Textarea"]').MobTextarea();
        }
    };
    window.mobui = mobui;

    $(function() {
        mobui.init();
    });
})(jQuery);

module.exports = window.mobui;
